﻿using Blog.webapi.Utility.ApiResult;
using Blog.webapi.Utility;
using EiiF_Blog;
using EiiFBlog.IServer;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using AutoMapper;
using EiiF_Blog.DTO;

namespace Blog.webapi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    [Authorize]
    public class AuthorController : ControllerBase
    {
        private readonly IAuthorService _authorService;
        public AuthorController(IAuthorService authorService)
        {
            this._authorService = authorService;
        }

        [HttpPost("Create")]
        public async Task<ApiResult> Create(string name,string username,string password)
        {
            Author author = new Author
            {
                Name = name,
                Username = username,
                Password = Md5Encode.MD5Encrypt32(password)

            };
            var repeat =await _authorService.Find(c => c.Name == name);
            if(repeat!=null) return ApiResultHelper.Error("作者名重复");
            var a = await _authorService.Create(author);
            if (a)
            {
                return ApiResultHelper.Success(author);
            }
            else
            {
                return ApiResultHelper.Error("添加失败");
            }
        }

        [HttpPut("Edit")]
        public async Task<ApiResult> Edit(string name)
        {
            int id =Convert.ToInt32(this.User.FindFirst("Id").Value);
            var author = await _authorService.Find(id);
            author.Name = name;
            bool b = await _authorService.Edit(author);
            if (b)
            {
                return ApiResultHelper.Success("修改成功");
            }
            else
            {
                return ApiResultHelper.Error("修改失败");
            }
        }

        [AllowAnonymous]
        [HttpGet("FindAuthor")]
        public async Task<ApiResult> FindAuthor([FromServices]IMapper imapper,int id)
        {
            var author = await _authorService.Find(id);
            var Author = imapper.Map<AuthorDto>(author);
            return ApiResultHelper.Success(Author);
        }
    }
}
